#include"Stack.h"
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#include<string.h>
// 初始化栈
void StackInit(Stack* ps)
{
	assert(ps);
	ps->array = (STDataType*)malloc(sizeof(STDataType*) * 3);
	if (ps->array == NULL) {
		assert(0);
		return;
	}
	ps->capacity = 3;
	ps->size = 0;
}
//栈的扩容
void CheckSrack(Stack* ps) {
	if (ps->size == ps->capacity) {
		int newcapacity = ps->capacity * 2;
		STDataType* temp = (STDataType*)malloc(sizeof(STDataType*) * newcapacity);
		if (temp == NULL) {
			assert(0);
			return;
		}
		memcpy(temp, ps->array, sizeof(STDataType)*ps->size);
		free(ps->array);
		ps->array = temp;
		ps->capacity = newcapacity;
	}
}
// 入栈
void StackPush(Stack* ps, STDataType data){
	assert(ps);
	CheckSrack(ps);
	ps->array[ps->size]=data;
	ps->size++;
}
// 出栈
void StackPop(Stack* ps){
	if (StackEmpty(ps)) {
		return;
	}
	ps->size--;
}
// 获取栈顶元素
STDataType StackTop(Stack* ps){
	assert(!StackEmpty(ps));
	return ps->array[ps->size - 1];
}
// 获取栈中有效元素个数
int StackSize(Stack* ps){
	assert(ps);
	return ps->size;
}
// 检测栈是否为空，如果为空返回非零结果，如果不为空返回0 
int StackEmpty(Stack* ps){
	assert(ps);
	if (ps->size == 0) {
		return 1;
	}
	else {
		return 0;
	}
}
// 销毁栈
void StackDestroy(Stack* ps){
	assert(ps);
	if (ps->array) {
		free(ps->array);
		ps->array = NULL;
		ps->capacity = 0;
		ps->size = 0;
	}
}


int main() {
	Stack s;
	StackInit(&s);
	StackPush(&s, 5);
	StackPush(&s, 6); 
	StackPush(&s, 7); 
	StackPush(&s, 8);
	printf("%d\n", StackTop(&s));
	StackPop(&s);
	printf("%d\n", StackTop(&s));
	printf("%d\n", StackSize(&s));
	StackDestroy(&s);
	return 0;
}

